package com.ly.lypopupwindowdemo.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ly.lypopupwindowdemo.R;

import java.util.List;

/**
 * Created by liying on 2017/7/18.
 * http://www.jianshu.com/p/99b244798108
 * http://www.jianshu.com/p/99b244798108
 * http://www.jianshu.com/p/99b244798108
 */

public class LyPickerView extends ScrollView {

    private Context context;

    private List<String> mData;

    private Paint mLinePaint;

    /**
     * 宽，高，显示的TextView的高度（只是TextView的高度，不算margin）
     */
    private int mWidth, mHeight, mTextHeight;

    /**
     * TextView父容器
     */
    private LinearLayout mTextGroup;

    /**
     * 屏幕的密度
     */
    private float mDensity;

    /**
     * 字体的大小
     */
    private float mTextSize;

    /**
     * 根据字体大小来控制整个控件的高度
     */
    private float mWrapContentHeight;

    /**
     * 当前选中的position
     */
    private int position, tempPosition = -1;
    private int scrollY;

    public LyPickerView(Context context) {
        this(context, null);
    }

    public LyPickerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LyPickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        /**
         * 注释：scrollView滑动到极限的时候不显示提示
         */
        setOverScrollMode(OVER_SCROLL_NEVER);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PickerView, defStyleAttr, 0);

        try {
            mTextSize = a.getDimension(R.styleable.PickerView_textSize, 25);
            mDensity = getResources().getDisplayMetrics().density;

            mTextHeight = (int) ((mDensity + 0.5) * mTextSize);

            mWrapContentHeight = mTextHeight * 10;//6
        } finally {

            a.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /**
         * 更改测量方法，指定高度为mWrapContentHeight
         */
        mWidth = measureWidth(widthMeasureSpec);
        mHeight = (int) mWrapContentHeight;
        setMeasuredDimension(mWidth, mHeight);

    }

    private int measureWidth(int widthMeasureSpec) {

        int mode = MeasureSpec.getMode(widthMeasureSpec);
        switch (mode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                return (int) mWrapContentHeight;
            case MeasureSpec.EXACTLY:
            default:
                return MeasureSpec.getSize(widthMeasureSpec);
        }

    }

    /**
     * ScrollView滑动监听
     *
     * @param l
     * @param t
     * @param oldl
     * @param oldt
     */
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        /**
         * 计算出当前在两条线里的positiono
         */
        position = (t + mTextHeight) / (mTextHeight * 2);

        if (tempPosition != position) {
            int size = mTextGroup.getChildCount();
            for (int i = 0; i < size; i++) {
                TextView tv = (TextView) mTextGroup.getChildAt(i);
                if (position + 2 == i) {//+1
                    tv.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
                } else {
                    tv.setTextColor(getResources().getColor(android.R.color.holo_blue_light));
                }
            }
        }
        tempPosition = position;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {


        /**
         * 因为ScrollView没有停止滑动的监听，所以利用onTouchEvert
         * 来取巧，在手指离开屏幕的30s之后判断是否和原来的scrooY一样
         * 如果一样则进入，如果不一样，则设置为一样。
         */


        if (ev.getAction() == MotionEvent.ACTION_UP) {
            scrollY = getScrollY();
            postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (scrollY == getScrollY()) {
                        /**
                         * 获得每次松手后scrollY相对于TextView高度的偏移量
                         */
                        int offset = scrollY % (mTextHeight * 2);

                        /**
                         * 如果偏移量大于TextView高度的一半
                         * 则进入到下一个
                         */
                        if (offset > mTextHeight) {
                            smoothScrollTo(0, scrollY - offset + (mTextHeight * 2));
                        } else {
                            smoothScrollTo(0, scrollY - offset);
                        }
                    } else {
                        scrollY = getScrollY();
                        post(this);
                    }
                }
            }, 30);
        }
        return super.onTouchEvent(ev);

    }

    /**
     * 设置fling速度为原来的1/3
     *
     * @param velocityY
     */
    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 3);
    }

    /**
     * 设置数据源
     */
    public void setData(List<String> data) {
        mData = data;
        init();
    }

    private void init() {

        mTextGroup = new LinearLayout(context);
        mTextGroup.setOrientation(LinearLayout.VERTICAL);
        mTextGroup.setGravity(Gravity.CENTER);
        addView(mTextGroup);

        mTextGroup.addView(createTextView(""));
        mTextGroup.addView(createTextView(""));
        for (int i = 0; i < mData.size(); i++) {
            mTextGroup.addView(createTextView(mData.get(i) + ""));
        }
        mTextGroup.addView(createTextView(""));
        mTextGroup.addView(createTextView(""));

        /**
         * 设置背景，画两条线
         */
        setBackground(new Drawable() {
            @Override
            public void draw(Canvas canvas) {
                /**
                 * 这里把两条线之间的距离设置为了两个TextView的高度
                 */

                canvas.drawLine(
                        mWidth * 0.1f,
                        mHeight / 2 - mTextHeight,
                        mWidth * 0.9f,
                        mHeight / 2 - mTextHeight,
                        mLinePaint
                );
                canvas.drawLine(
                        mWidth * 0.1f,
                        mHeight / 2 + mTextHeight,
                        mWidth * 0.9f,
                        mHeight / 2 + mTextHeight,
                        mLinePaint
                );
            }

            @Override
            public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {

            }

            @Override
            public void setColorFilter(@Nullable ColorFilter colorFilter) {

            }

            @Override
            public int getOpacity() {
                return 0;
            }
        });

        mLinePaint = new Paint();
        mLinePaint.setAntiAlias(true);
        mLinePaint.setStrokeWidth(1);
        mLinePaint.setColor(getResources().getColor(android.R.color.holo_blue_dark));
        setPosition(0);

    }

    private void setPosition(int position) {
        this.position = position;
        if (position == 0) {
            post(new Runnable() {
                @Override
                public void run() {
                    scrollTo(0, 1);
                }
            });
            return;
        }
        post(new Runnable() {
            @Override
            public void run() {
                scrollTo(0, LyPickerView.this.position * (mTextHeight * 2));
            }
        });

    }

    private TextView createTextView(String str) {
        TextView tv = new TextView(context);
        tv.setText(str);
        tv.setTextColor(getResources().getColor(android.R.color.darker_gray));
        tv.setTextSize(mTextSize);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mTextHeight);

        params.bottomMargin = mTextHeight / 2;
        params.topMargin = mTextHeight / 2;

        tv.setLayoutParams(params);
        return tv;
    }

    /**
     * 获取position
     *
     * @return
     */
    public int getPosition() {
        return position;
    }

}
